package com.io.smartappframe.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.io.commonlib.helper.LogHelper
import com.io.commonlink.mqtt.MQTTManager
import kotlinx.coroutines.*
import org.eclipse.paho.client.mqttv3.*

class MyMqttService : Service(), MqttCallbackExtended, IMqttActionListener {
    private val TAG = MyMqttService::class.java.simpleName
    private lateinit var job: Job
    private lateinit var scope: CoroutineScope

    private var mqttManager: MQTTManager = MQTTManager(
        this,
        mqttUrl = "tcp://mqtt-cn-4590tgge605.mqtt.aliyuncs.com:1883",
        clientId = "GID_Face@@@V9_A181FRI_P13_000001af",
        instanceId = "mqtt-cn-4590tgge605",
        accessKey = "LTAI8WRPpX2kOTLm",
        secretKey = "CMZpWsUz4IV2BkJijw26BROzKC6EOe"
    )
    override fun onCreate() {
        super.onCreate()
        job = Job()
        scope = CoroutineScope(job)
        mqttManager.initMqtt()
        mqttManager.setMqttCallback(this)
        mqttManager.setMqttActionListener(this)
        connectMqtt()
    }

    /**
     * 连接mqtt
     */
    fun connectMqtt() {
        try {
            scope.launch(Dispatchers.IO) {
                mqttManager.connectMqtt()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            LogHelper.e(TAG, "connectMqtt--Exception:${e.message}")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mqttManager?.let {
            mqttManager.destroy()
        }
        job.cancel()
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onUnbind(intent: Intent?): Boolean {
        unsubscribeMqttTopic()
        return super.onUnbind(intent)
    }

    //region 实现MqttCallbackExtended接口
    override fun connectComplete(reconnect: Boolean, serverURI: String?) {
        LogHelper.d(TAG, "connectComplete reconnect:$reconnect, serverURI:$serverURI")
    }

    override fun messageArrived(topic: String?, message: MqttMessage?) {
        LogHelper.i(TAG, "messageArrived--topic:$topic; \n message:$message")

    }

    override fun connectionLost(cause: Throwable?) {
        cause?.let {
            it.message?.let { it0 ->
                LogHelper.e(TAG, "connectionLost: $it0")
            }
        }
    }

    override fun deliveryComplete(token: IMqttDeliveryToken?) {
        token?.let {
            LogHelper.d(TAG, "deliveryComplete--token:${token}")
        }
    }
    //endregion

    //region 实现IMqttActionListener接口
    override fun onSuccess(asyncActionToken: IMqttToken?) {
        LogHelper.i(TAG, "IMqttActionListener--onSuccess")
    }

    override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
        exception?.printStackTrace()
        LogHelper.i(TAG, "IMqttActionListener--onFailure--${exception?.message}")
    }
    //endregion

    //region 私有方法
    //订阅消息
    private fun subscribeMqttMessage() {
        mqttManager.subscribeToTopic("Face", 1)
    }

    //取消订阅消息
    private fun unsubscribeMqttTopic() {
        mqttManager.unsubscribe("Face")
    }

    //endregion

}
